<template>
  <el-container class="me-top">
    <el-header>
      <el-row>
        <el-col :span="18" style="text-align: left;">
          <el-form ref="form" :model="formInline" :inline="true">
            <el-form-item label="名称:">
              <el-input v-model="formInline.name" />
            </el-form-item>
            <el-button icon="el-icon-search" circle @click="search" />
          </el-form>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="add">添加</el-button>
          <el-popconfirm
            confirm-button-text="确认"
            cancel-button-text="取消"
            icon="el-icon-info"
            icon-color="red"
            title="确认全部删除？"
            @onConfirm="BatchRemove"
          >
            <el-button slot="reference" :disabled="flag" type="danger">批量删除</el-button>
          </el-popconfirm>
        </el-col>
      </el-row>
    </el-header>
    <el-main>
      <el-table :data="tableData" border stripe style="width: 100%" @selection-change="selectedRows">
        <el-table-column
          type="selection"
          width="55"
        />
<!--        <el-table-column prop="id" label="编号" align="center" />-->
        <el-table-column prop="username" label="员工姓名" align="center" />
        <el-table-column prop="sex" label="性别" align="center" :formatter="formatterSex" />
        <el-table-column prop="headImage" label="头像" align="center" />
        <el-table-column prop="tele" label="tele" align="center" />
        <el-table-column prop="department.name" label="部门名称" align="center" />
        <el-table-column prop="roles" label="拥有角色" align="center" >
          <template slot-scope="scope">
            <el-tag v-for=" item in scope.row.roles" style="margin-right: 5px;">
              {{item.name}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="edit(scope.row)">编辑</el-button>
            <el-popconfirm
              confirm-button-text="确认"
              cancel-button-text="取消"
              icon="el-icon-info"
              icon-color="red"
              title="你确定要删除当前数据？"
              @onConfirm="remove(scope.row)"
            >
              <el-button slot="reference" type="danger" size="small">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :page-sizes="pageSizes"
          :page-size="10"

          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <!-- :current-page="2"-->
      </div>
    </el-main>
    <!--  新增、编辑-->
    <el-dialog title="新增用户" :visible.sync="dialogFormVisible">
      <el-form ref="addForm" :model="addForm" label-width="100px" status-icon :rules="rules">
        <input v-model="addForm.id" type="hidden">
        <el-form-item prop="username" label="员工姓名">
          <el-input v-model="addForm.username" suffix-icon="el-icon-user" />
        </el-form-item>
        <el-form-item prop="age" label="年龄">
          <el-input v-model="addForm.age" />
        </el-form-item>
        <el-form-item prop="sex" label="性别">
          <el-radio v-model="addForm.sex" :label="true">男</el-radio>
          <el-radio v-model="addForm.sex" :label="false">女</el-radio>
        </el-form-item>
        <el-form-item prop="headImage" label="头像">
          <el-input v-model="addForm.headImage" />
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input v-model="addForm.password" />
        </el-form-item>
        <el-form-item prop="tele" label="tele">
          <el-input v-model="addForm.tele" />
        </el-form-item>
        <el-form-item prop="tele" label="部门名称">
          <el-select v-model="addForm.department.id" placeholder="请选择" @click="getValue">
            <el-option
              v-for="item in dept"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="roles" label="角色名称">
          <el-transfer
            filterable
            :titles = "['所有角色','拥有角色']"
            :props="{ key: 'id', label: 'name' }"
            @change="ChangedRole"
            filter-placeholder="请输入关键字"
            v-model="addForm.roles"
            :data="roleData" style="padding-left: 28px;">
          </el-transfer>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </el-container>

</template>

<script>
export default {
  data: function() {
    return {
      flag: true,
      addForm: {
        id: '',
        username: '',
        age: '',
        sex: '',
        headImage: '',
        tele: '',
        password: '',
        department: {
          id: ''
        },
        roles :[]
      },
      page: 1, // 第几页
      size: 10, // 每页条数
      total: 0,
      pageSizes: [5, 10, 15, 20],
      tableData: [],
      formInline: {
        name: '',
        date: ''
      },
      dialogFormVisible: false,
      selectRows: {},
      dept: [],
      deptId: '',
      rules: {
        username: [
          { required: true, message: '请输入员工名称', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        tele: [
          { required: true, message: '请输入电话号码', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '请输入年龄', trigger: 'blur' }
        ]
      },
      roleData :[], //穿梭框数据
      checkedRole : [], //穿梭框选中的的数据数据
    }
  },
  mounted() {
    this.loadListData()
    this.deptname()
    this.findAllRole()
  },
  methods: {
    findAllRole(){
      this.$http.get('/role/findAll').then((res) => {
        this.roleData = res.data.data
      }).catch(error => {
        console.log(error)
      })
    },
    ChangedRole(val){
      this.checkedRole = val
    },
    getRadioValue(val) {
      this.sexRadio = val
    },
    formatterSex(val) {
      return val.sex ? '男' : '女'
    },
    getValue(val) {
      this.deptId = val
    },
    search() {
      this.loadListData()
    },
    deptname() {
      this.$http.get('/department/findAll').then((res) => {
        this.dept = res.data.data
      }).catch(error => {
        console.log(error)
      })
    },
    submit() {
      let check = this.checkedRole
      let param = this.addForm
      let temp = []
      for (let i = 0; i < check.length; i++) {
        temp.push({"id":check[i]})
      }
      param.roles = temp
      if (this.addForm.id) { // 修改
        this.$http.put('/employee/update', param).then((res) => {
          if (res.data.success) {
            this.$message.success(res.data.message)
            this.loadListData()
            this.dialogFormVisible = false
          } else {
            // eslint-disable-next-line no-undef
            this.$message.error('修改失败[' + error.message + ']')
          }
        }).catch(error => {
          console.log(error)
        })
      } else { // 添加
        this.$http.post('/employee/insert', param).then((res) => {
          if (res.data.success) {
            this.$message.success(res.data.message)
            this.loadListData()
            this.dialogFormVisible = false
          } else {
            // eslint-disable-next-line no-undef
            this.$message.error('添加失败[' + error.message + ']')
          }
        }).catch(error => {
          console.log(error)
        })
      }
    },
    add() {
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['addForm'].resetFields()
      })
      for (let key in this.addForm){
        if (key !== 'department'){
          this.addForm[key] = ''
        }
      }
      this.addForm.department.id = this.deptId
      this.addForm.roles = []
    },
    edit(row) {
      this.dialogFormVisible = true
      this.checkedRole = []
      let roles = row.roles
      roles.forEach(item =>{
        this.checkedRole.push(item.id)
      })
      this.$nextTick(() => {
        this.addForm = Object.assign({}, row)
        this.addForm.roles = this.checkedRole
        console.log(this.addForm.sex)
      })

    },
    remove(row) {
      this.$http.delete('/employee/deleteById/' + row.id).then(res => {
        if (res.data.success) {
          this.$message.success(res.data.message)
          this.loadListData()
        } else {
          // eslint-disable-next-line no-undef
          this.$message.error('删除失败[' + error.message + ']')
        }
      }).catch(error => {
        this.$message.error('删除失败[' + error.message + ']')
      })
    },
    BatchRemove() {
      const ids = this.selectRows.map(function(obj) {
        return obj.id
      })
      console.log(ids.toString())
      this.$http.post('/employee/batchDeleteByIds', { ids: ids }).then(res => {
        if (res.data.success) {
          this.$message.success(res.data.message)
          this.loadListData()
        } else {
          // eslint-disable-next-line no-undef
          this.$message.error('删除失败[' + error.message + ']')
        }
      }).catch(error => {
        this.$message.error('删除失败[' + error.message + ']')
      })
    },
    handleSizeChange(val) {
      this.size = val
      this.loadListData()
    },
    handleCurrentChange(currentPage) {
      this.page = currentPage
      this.loadListData()
    },
    loadListData() {
      this.loading = true
      // vue加载完成，发送ajax请求动态获取数据
      const param = {
        'pageNo': this.page,
        'pageSize': this.size,
        'keyWord': this.formInline.name
      }
      this.$http.post('/employee/findForList', param).then((res) => {
        this.tableData = res.data.data.result
        this.total = res.data.data.total
        this.page = res.data.data.pageNo
      }).catch(error => {
        console.log(error)
      })
    },
    selectedRows(rows) {
      console.log(rows)
      if (rows.length > 0) {
        this.flag = false
        this.selectRows = rows
      } else {
        this.flag = true
      }
    }
  }
}
</script>

<style scoped>
  .me-top {
    padding-top: 20px;
  }
</style>
